package ljt.music.module.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

import com.r0adkll.slidr.Slidr;
import com.r0adkll.slidr.model.SlidrConfig;
import com.r0adkll.slidr.model.SlidrInterface;

import java.util.List;

/**
 * @author jiangtao
 * @date 2017/11/25
 */

public class BaseActivity extends AppCompatActivity {

    protected SlidrInterface slidrInterface;
    private FragmentManager supportFragmentManager;

    /**
     * 显示Fragment
     *
     * @param container
     * @param fragment
     * @param tag
     */
    public void showFragment(int container, Fragment fragment, String tag) {
        if (supportFragmentManager == null) {
            supportFragmentManager = getSupportFragmentManager();
        }
        FragmentTransaction transaction = supportFragmentManager.beginTransaction();
        List<Fragment> fragments = supportFragmentManager.getFragments();
        for (Fragment f : fragments) {
            transaction.hide(f);
        }
        if (fragment.isAdded()) {
            transaction.show(fragment);
        } else {
            transaction.add(container, fragment, tag);
        }
        transaction.commitAllowingStateLoss();
    }

    /**
     * 初始化 Toolbar
     *
     * @param toolbar
     * @param homeAsUpEnabled
     * @param title
     */
    protected void initToolBar(Toolbar toolbar, boolean homeAsUpEnabled, String title) {
        toolbar.setTitle(title);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(homeAsUpEnabled);
    }

    /**
     * 初始化滑动返回
     */
    protected void initSlidable() {
        SlidrConfig config = new SlidrConfig.Builder()
                .edge(true)
                .build();
        slidrInterface = Slidr.attach(this, config);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initSlidable();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onBackPressed() {
        // Fragment 逐个出栈
        int count = getSupportFragmentManager().getBackStackEntryCount();
        if (count == 0) {
            super.onBackPressed();
        } else {
            getSupportFragmentManager().popBackStack();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
